package com.example.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.config.PublisherAware;
import com.example.blog.domain.Response;
import com.example.blog.domain.SignIn;
import com.example.blog.dto.operationalLogs.OperationLogsDto;
import com.example.blog.event.publisher.LoggingApplicationEvent;
import com.example.blog.note.LogInfo;
import com.example.blog.service.impl.SignInServiceImpl;
import com.example.blog.utils.IpUtil;
import com.example.blog.utils.JwtUtils;
import com.example.blog.utils.RedisStorage;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@RestController
@Transactional
@RequestMapping("/signIn")
public class SignInController extends BaseController{
    private final SignInServiceImpl signInService;
    private final RedisStorage redisStorage;
    private final PublisherAware loggingPublisherAware;
    @Autowired
    public SignInController(RedisStorage redisStorage,SignInServiceImpl signInService, PublisherAware loggingPublisherAware){
        this.redisStorage = redisStorage;
        this.signInService = signInService;
        this.loggingPublisherAware = loggingPublisherAware;
    }
    //获取用户所有签到信息
    @LogInfo("获取用户所有签到信息")
    @GetMapping("/getAll/{index}")
    public Response getAll(@PathVariable("index") int index){
         HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
         Claims claims =  JwtUtils.checkToken( request.getHeader("token"));
         IPage page = new Page(index,7);
         LambdaQueryWrapper<SignIn> wrapper = new LambdaQueryWrapper<>();
         wrapper.orderByDesc(SignIn::getDateTime).eq(SignIn::getUid,claims.get("uid"));
         return new Response(Response.SUCCEED_CODE,"获取成功",signInService.page(page,wrapper).getRecords());
     }
    //新增签到信息
    @LogInfo("新增签到")
    @PostMapping("/insert")
    public Response insert(@Validated @RequestBody SignIn sign) throws ParseException {
        OperationLogsDto logsVo = new OperationLogsDto(
                1, IpUtil.getIpAddress(getHttpInfo()), "新增签到", getLogSign(), "签到用户id：".concat(String.valueOf(sign.getUid())));
        boolean insert = false;
        try {
            boolean statue = redisStorage.checkSingInStatue(sign.getUid());
            SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
            Date date = new Date(System.currentTimeMillis());
            DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = dFormat.format( df.parse( sign.getDateTime()));
            logsVo.setOutcome(0);
            if(!statue && time.equals(formatter.format(date)) ){
                redisStorage.insertSingIn(sign);
                insert = signInService.save(sign);
                logsVo.setOutcome(1);
            }
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
        }catch (Exception e){
            loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
            throw e;
        }
         return new Response(Response.SUCCEED_CODE,"新增签到",insert);
     }
    //删除签到信息
    @LogInfo("删除签到信息")
    @DeleteMapping("/del/{id}")
    public Response del(@PathVariable("id") long id){
        OperationLogsDto logsVo = new OperationLogsDto(
                -1, IpUtil.getIpAddress(getHttpInfo()), "删除签到信息", getLogSign(), "签到用户id：".concat(String.valueOf(id)));
        boolean remove = false;
       try{
           LambdaQueryWrapper<SignIn> sign = new LambdaQueryWrapper<>();
           sign.eq(SignIn::getId,id);
           remove = signInService.remove(sign);
           logsVo.setOutcome(1);
           loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
       }catch (Exception e){
           logsVo.setOutcome(0);
           loggingPublisherAware.publisher(new LoggingApplicationEvent(logsVo));
           throw e;
       }
        return new Response(Response.SUCCEED_CODE,"删除签到信息",remove);
    }
    //判断用户今日是否签到
    @LogInfo("判断用户今日是否签到")
    @GetMapping("/statue")
    public Response statue(){
         boolean statue = redisStorage.checkSingInStatue(getLogSign().getUid());
        return new Response(Response.SUCCEED_CODE,"是否签到",statue);
    }

    //获取用户当前的积分
    @LogInfo("获取用户当前的积分")
    @GetMapping("/integralAdd")
    public Response integral(){
        QueryWrapper<SignIn> wrapper = new QueryWrapper<>();
        wrapper.select("sum(integral) as integral").eq("uid",getLogSign().getUid());
        return new Response(Response.SUCCEED_CODE,"获取用户当前的积分",signInService.getMap(wrapper).get("integral"));
    }

}
